﻿#pragma once
#include<iostream>
#include<vector>
#include<list>
using namespace std;
namespace QL
{
	template<class T>
	struct Myless //小于类
	{
		bool operator()(const T& x, const T& y)
		{
			return x < y;
		}
	};

	template<class T>
	struct MyGreater //大于类
	{
		bool operator()(const T& x, const T& y)
		{
			return x > y;
		}
	};

	template<class T,class Container= vector<T>,class Compare=Myless<T>>
	class PriorityQueue
	{
	public:
		PriorityQueue() = default;
		template <class InputIterator>
		PriorityQueue(InputIterator first, InputIterator last)
		{
			while (first != last)
			{
				_con.push_back(*first);
				++first;
			}

			//建堆
			for (size_t i = (_con.size() - 1 - 1) / 2; i >= 0; i--)
			{
				Adjust_Down(i, size());
			}
		}

		void push(const T& val)
		{
			_con.push_back(val);
			Adjust_Up(_con.size()-1);
		}
		
		T& top()
		{
			return _con.front();
		}

		void pop()
		{
			swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();
			Adjust_Down(0 , _con.size());
		}

		void Adjust_Up(size_t child)
		{
			Compare cmp;
			while (child > 0)
			{
				size_t parent = (child - 1) / 2;
				if (cmp(_con[parent] , _con[child]))
				{
					swap(_con[parent], _con[child]);
					child = parent;
				}
				else
				{
					break;
				}
			}
		}

		void Adjust_Down(size_t parent,size_t n)
		{
			size_t child = 2 * parent + 1;
			Compare cmp;
			while (child < n)
			{
				if ((child + 1 < n) && cmp( _con[child] , _con[child + 1]))
				{
					child++;
				}
				if (cmp(_con[parent] , _con[child]))
				{
					swap(_con[parent], _con[child]);
					parent = child;
					child = 2 * parent + 1;
				}
				else
				{
					break;
				}
			}
		}

		size_t size()
		{
			return _con.size();
		}

		bool empty()
		{
			return _con.empty();
		}

		void print()
		{
			for (int& v : _con)
			{
				cout << v << " ";
			}
			cout << endl;
		}
	private:
		Container _con;
	};

	void Test_PriorityQueue1()
	{
		PriorityQueue<int> pq;
		pq.push(10);
		pq.push(15);
		pq.push(5);
		pq.push(6);
		pq.print();

		while (!pq.empty())
		{
			cout << pq.top() << " ";
			pq.pop();
		}
		cout << endl;
	}

	void Test_PriorityQueue2()
	{
		vector<int> v = { 10,5,12,30,6,8,9,11,28 };
		list<int> lt= { 10,5,12,30,6,8,9,11,28 };
		PriorityQueue<int> pq1(v.begin(), v.end());
		pq1.print();
		PriorityQueue<int> pq2(lt.begin(), lt.end());
		pq2.print();
	}

	void Test_PriorityQueue3()
	{
		PriorityQueue<int,vector<int>> pq;
		pq.push(10);
		pq.push(6);
		pq.push(20);
		pq.push(300);
		pq.push(100);
		pq.push(50);
		pq.push(400);
		pq.print();
		while (!pq.empty())
		{
			cout << pq.top() << " ";
			pq.pop();
		}
		cout << endl;
	}
}
